#!/usr/bin/env python
#Aplicacion para filtrar o modificar
#contenido de conexiones http
#@created 2 abril 2011
#@author jlgc <sinolorsinvision@gmail.com>

import sys

#libreria para servicios http
try:
    from twisted.web import proxy
    from twisted.web.proxy import Proxy, ProxyRequest, ProxyClient, ProxyClientFactory
    from twisted.web import http
    from twisted.python import log
except:
    print "SE NECESITA LIBRERIA -> PYTHON TWISTED"
    exit(-1)

#envia log a terminal
log.startLogging(sys.stdout)

PROXY_PORT = 8009
print "ESCUCHANDO EN EL PUERTO " + str(PROXY_PORT)
print "PORFAVOR CONFIGURE SU NAVEGADOR A ESTE PUERTO"

#lista de filtros
from filters import filters
import re

class FilterProxyClient(ProxyClient):
    """
    cliente proxy para conectarse al servidor pedido
    por el cliente
    """

    def __init__ (self, *args):
        self.is_html = False
        self.line_mode = True
        ProxyClient.__init__(self, *args)

    def handleHeader(self, key, value):
        #print "HEAD: %s=%s" % (key, value)
        ProxyClient.handleHeader(self, key, value)

        url = self.headers['host']+self.rest
        print 'URL:'+url
        if key.lower() == 'content-type':
            #RECOGE LOS FILTROS QUE SE ACTIVAN SEGUN EL CONTENIDO
            #@todo falto por sitio
            for fa in filters.get_filters():
                #solo los del tipo de contenido
                if value.split(';')[0] == fa.content_type:
                    #y que este en la ubicacion tal
                    for urlrex in fa.includes:
                        if re.search(urlrex, url):
                            filters.activate(fa)
                
        
    def lineReceived(self, line):
        #print "lineReceived: %s" % (line)
        ProxyClient.lineReceived(self, line)
        
    def handleResponsePart(self, buffer):
        """
        Modifica la respuesta a traves de los filtros
        """

        #SE PROCESA LA INFORMACION A TRAVES DE LOS FILTROS
        #ACTIVOS
        for fa in filters.get_filters():
            print fa
            if fa.active:
                nbuffer = fa.process(buffer)
                if nbuffer:
                    buffer = nbuffer


        ProxyClient.handleResponsePart(self, buffer)



class FilterProxyClientFactory(ProxyClientFactory):
    
    def __init__(self, *args):
        ProxyClientFactory.__init__(self,*args)
 
    def buildProtocol(self, addr):
        client = ProxyClientFactory.buildProtocol(self, addr)
        client.__class__ = FilterProxyClient
        return client


class FilterProxyRequest(ProxyRequest):
    protocols = {'http': FilterProxyClientFactory}
               
    def __init__ (self, *args):
        ProxyRequest.__init__(self, *args)

class FilterProxy(Proxy):
    def __init__(self, *args):
        Proxy.__init__(self, *args)

    def requestFactory(self, *args):
        return FilterProxyRequest( *args)


class FilterProxyFactory(http.HTTPFactory):
    """
    servidor de proxy
    """
    def __init__(self, *args):
        http.HTTPFactory.__init__(self, *args)

    def buildProtocol(self, addr):
        protocol = FilterProxy()
        return protocol

        
        


if __name__ == "__main__":
    from twisted.internet import reactor
    proxy = FilterProxyFactory()
    reactor.listenTCP(PROXY_PORT, proxy)
    reactor.run()



